package time

import (
	"database/sql/driver"
	"fmt"
	"time"
)

//DefaultFormat default time format layout , like format pattern YYYY-MM-dd HH:mm:ss in java
const DefaultFormat = "2006-01-02 15:04:05"

// Time alias time.time
type Time struct {
	time.Time
}

// Now current time
func Now() Time {
	return Time{time.Now()}
}

// MarshalJSON implement json Marshaller
func (t Time) MarshalJSON() ([]byte, error) {
	var zero time.Time
	if t.UnixNano() == zero.UnixNano() {
		return []byte("null"), nil
	}
	var formatTime = t.Format(DefaultFormat)
	var timeString = fmt.Sprintf("\"%s\"", formatTime)
	return []byte(timeString), nil
}

//UnmarshalJSON implement json UnMarshaller
func (t *Time) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		t = nil
	}
	if b == nil || len(b) == 0 {
		return nil
	}
	var t1, err = time.ParseInLocation(`"`+DefaultFormat+`"`, string(b), time.Local)
	if err != nil {
		return nil
	}
	*t = Time{Time: t1}
	return nil
}

// String implement Stringer interface
func (t Time) String() string {
	return t.Format(DefaultFormat)
}

// Value insert timestamp into mysql need this function.
func (t Time) Value() (driver.Value, error) {
	return t.Time, nil
}

// Scan value of time.Time
func (t *Time) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = Time{value}
		return nil
	}
	return fmt.Errorf("can not convert %v to time.Time", v)
}
